package com.senlingspace.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.core.domain.entity.SysDept;
import com.senlingspace.common.core.domain.entity.SysUser;
import com.senlingspace.common.enums.*;
import com.senlingspace.common.exception.UtilException;
import com.senlingspace.common.utils.*;
import com.senlingspace.common.enums.LakalaPaymentTypeEnum;
import com.senlingspace.common.enums.LakalaTradeStateEnum;
import com.senlingspace.system.domain.*;
import com.senlingspace.system.domain.dto.ShiftManagementDto;
import com.senlingspace.system.domain.vo.*;
import com.senlingspace.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.senlingspace.system.service.ISlkjShiftManagementService;
import org.springframework.util.CollectionUtils;

/**
 * 员工交接班记录Service业务层处理
 *
 * @author SenlingSpace
 * @date 2024-07-24
 */
@Service
public class SlkjShiftManagementServiceImpl implements ISlkjShiftManagementService {
    private static final Logger log = LoggerFactory.getLogger(SlkjShiftManagementServiceImpl.class);
    @Autowired
    private SlkjShiftManagementMapper slkjShiftManagementMapper;

    @Autowired
    private SlkjOrderMapper slkjOrderMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SlkjShopMapper shopMapper;
    @Autowired
    private SlkjOrderPricingSnapshotMapper slkjOrderPricingSnapshotMapper;
    @Autowired
    private SlkjShopMapper slkjShopMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SlkjShopProjectMapper slkjShopProjectMapper;


    /**
     * 查询员工交接班记录明细
     *
     * @param id 员工交接班记录主键
     * @return 员工交接班记录
     */
    @Override
    public AjaxResult selectSlkjShiftManagementById(Long id) {
        SlkjShiftManagement slkjShiftManagement = slkjShiftManagementMapper.selectSlkjShiftManagementById(id);
        if (slkjShiftManagement == null) {
            log.info("员工今日未上班");
            return AjaxResult.warn("员工今日未上班！");
        }
        Long userId = slkjShiftManagement.getUserId();
        final ShiftManagementVo vo = new ShiftManagementVo();
        vo.setId(slkjShiftManagement.getId());
        vo.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
        vo.setShopName(slkjShiftManagement.getShopName());
        vo.setShopId(slkjShiftManagement.getShopId());
        vo.setUserId(slkjShiftManagement.getUserId());
        vo.setNickName(slkjShiftManagement.getNickName());
        vo.setStartTime(slkjShiftManagement.getStartTime());
        vo.setEndTime(slkjShiftManagement.getEndTime());
        vo.setStatus(slkjShiftManagement.getStatus());
        vo.setDelFlag(slkjShiftManagement.getDelFlag());
        vo.setHandoverId(slkjShiftManagement.getHandoverId());

        if ("0".equals(slkjShiftManagement.getStatus())) {
            List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTimeList(slkjShiftManagement.getStartTime(), DateUtils.getNowDate());
            List<Pay> pays = new ArrayList<>();
            Pay pay = new Pay();

            // 统计退款金额
            AtomicLong cashAl = new AtomicLong(0);
            AtomicLong scanAl = new AtomicLong(0);
            if (CollectionUtils.isEmpty(slkjOrders)) {
                pay.setName("现金");
                pay.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
                pays.add(pay);

                Pay scan = new Pay();
                scan.setName("扫码");
                pays.add(scan);
                vo.setPays(pays);
                log.info("当前用户 [{}] 今日未产生订单！", userId);
            } else {
                // 最终所有返回数据，全部基于这个list
                List<SlkjOrder> nowUserOrderList = slkjOrders.stream()
                        .filter(order -> order.getCreateBy().equals(userId + "") && (order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()) ||
                                order.getPaymentStatus().equals(LakalaTradeStateEnum.PART_REFUND.name()) ||
                                order.getPaymentStatus().equals(LakalaTradeStateEnum.REFUND.name())))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(nowUserOrderList)) {
                    log.info("当前用户 [{}] 今日未产生订单！", userId);
                } else {
                    // 获取订单价格快照信息
                    Set<Long> orderIds = nowUserOrderList.stream().map(SlkjOrder::getOrderId).collect(Collectors.toSet());
                    Map<Long, List<SlkjOrderPricingSnapshot>> orderSnapMap = slkjOrderPricingSnapshotMapper.selectByOrderIds(Lists.newArrayList(orderIds))
                            .stream()
                            .collect(Collectors.groupingBy(SlkjOrderPricingSnapshot::getOrderId));

                    String oncash = "oncash", online = "online";
                    // 根据支付方式分组，如果是现金支付单独做为一个list，否则剩余的都视为线上支付
                    Map<String, List<SlkjOrder>> orderPaymentTypeMap = nowUserOrderList.stream()
                            .filter(order -> order.getSource().equals(OrderSource.SHOP.getCode()))
                            .collect(
                                    Collectors.groupingBy(order -> LakalaPaymentTypeEnum.INCASH.getCode().equals(order.getPaymentType()) ? oncash : online)
                            );

                    // 退款金额
                    nowUserOrderList.stream()
                            .filter(order -> order.getPaymentStatus().equals(LakalaTradeStateEnum.REFUND.name()) || order.getPaymentStatus().equals(LakalaTradeStateEnum.PART_REFUND.name()))
                            .forEach(order -> {
                                if (order.getPaymentType().equals(LakalaPaymentTypeEnum.INCASH.getCode())) {
                                    cashAl.addAndGet(order.getActualAmount());
                                } else {
                                    scanAl.addAndGet(order.getActualAmount());
                                }
                            });

                    // 处理现金支付
                    if (orderPaymentTypeMap.containsKey(oncash)) {
                        List<SlkjOrder> cashList = orderPaymentTypeMap.get(oncash);
                        pay.setRefund(MoneyUtils.fen2Yuan(cashAl.get()));
                        pay.setName("现金");
                        pay.setOrderNum(cashList.size());
                        pay.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
                        int goodsNum = 0;
                        int ticketNum = 0;
                        for (SlkjOrder o : cashList) {
                            List<SlkjOrderPricingSnapshot> snapshots = orderSnapMap.get(o.getOrderId());
                            // 101=门票、102=商品、103=门票+商品
                            switch (OrderType.fromCode(o.getOrderType())) {
                                case OT_101:
                                    ticketNum += snapshots.stream()
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();
                                    break;
                                case OT_102:
                                    goodsNum += snapshots.size();
                                    break;
                                case OT_103:
                                    ticketNum += snapshots.stream()
                                            .filter(i -> "TICKET".equals(i.getItemType()))
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();

                                    goodsNum += (int) snapshots.stream()
                                            .filter(i -> "GOODS".equals(i.getItemType()))
                                            .count();
                                    break;
                                default:
                                    break;
                            }
                        }
                        pay.setQuantity(goodsNum);
                        pay.setTicketNum(ticketNum);

                        long cashTotal = cashList.stream().mapToLong(SlkjOrder::getActualAmount).sum();
                        log.info("员工 [{}] 今日现金收款金额：{}分！", userId, cashTotal);
                        String yuan = MoneyUtils.fen2Yuan(cashTotal);
                        pay.setReceipts(yuan);

                        pay.setRefund(cashAl.get() > 0 ? MoneyUtils.fen2Yuan(cashAl.get()) : "0");
                        pays.add(pay);
                    } else {
                        Pay cashPay = new Pay();
                        cashPay.setName("现金");
                        cashPay.setRefund(MoneyUtils.fen2Yuan(cashAl.get()));
                        cashPay.setOrderNum(0);
                        pays.add(cashPay);
                    }


                    // 处理线上支付
                    if (orderPaymentTypeMap.containsKey(online)) {
                        Pay payScan = new Pay();
                        int goodsNum = 0;
                        int ticketNum = 0;
                        List<SlkjOrder> onlineList = orderPaymentTypeMap.get(online);
                        payScan.setName("扫码");
                        payScan.setRefund(MoneyUtils.fen2Yuan(scanAl.get()));
                        payScan.setOrderNum(onlineList.size());
                        for (SlkjOrder o : onlineList) {
                            List<SlkjOrderPricingSnapshot> snapshots = orderSnapMap.get(o.getOrderId());
                            // 101=门票、102=商品、103=门票+商品
                            switch (OrderType.fromCode(o.getOrderType())) {
                                case OT_101:
                                    ticketNum += snapshots.stream()
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();
                                    break;
                                case OT_102:
                                    goodsNum += snapshots.size();
                                    break;
                                case OT_103:
                                    ticketNum += snapshots.stream()
                                            .filter(i -> "TICKET".equals(i.getItemType()))
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();

                                    goodsNum += (int) snapshots.stream()
                                            .filter(i -> "GOODS".equals(i.getItemType()))
                                            .count();
                                    break;
                                default:
                                    break;
                            }
                        }
                        payScan.setQuantity(goodsNum);
                        payScan.setTicketNum(ticketNum);

                        long onlineTotal = onlineList.stream().mapToLong(SlkjOrder::getActualAmount).sum();
                        log.info("员工 [{}] 今日线上收款金额：{}分！", userId, onlineTotal);
                        String yuan = MoneyUtils.fen2Yuan(onlineTotal);
                        payScan.setReceipts(yuan);

                        payScan.setRefund(scanAl.get() > 0 ? MoneyUtils.fen2Yuan(scanAl.get()) : "0");
                        pays.add(payScan);
                    } else {
                        Pay scanPay = new Pay();
                        scanPay.setName("扫码");
                        scanPay.setRefund(MoneyUtils.fen2Yuan(scanAl.get()));
                        scanPay.setOrderNum(0);
                        pays.add(scanPay);
                    }

                }
                vo.setPays(pays);
            }

            pays = vo.getPays();
            // 计算应交现金
            vo.setShiftHandover(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
            if (!CollectionUtils.isEmpty(pays)) {
                Optional<Pay> paySum = pays.stream().filter(p -> p.getName().equals("现金")).findFirst();
                if (paySum.isPresent()) {
                    String receipts = paySum.get().getReceipts();
                    if (StringUtils.isNotBlank(receipts) && !"0".equals(receipts)) {
                        long total = MoneyUtils.yuan2Fen(receipts) + slkjShiftManagement.getPettyCash();
                        vo.setShiftHandover(MoneyUtils.fen2Yuan(total - cashAl.get()));
                    }
                }

                // 计算总收入，需要把退款的金额扣除
                long totalRefund = pays.stream().mapToLong(p -> MoneyUtils.yuan2Fen(p.getRefund())).sum();
                long totalReceipts = pays.stream()
                        .mapToLong(p -> MoneyUtils.yuan2Fen(p.getReceipts()))
                        .sum();
                vo.setTotalReceipts(MoneyUtils.fen2Yuan((totalReceipts - totalRefund)));

                // 计算总订单数
                Long orderNum = pays.stream()
                        .mapToLong(Pay::getOrderNum)
                        .sum();
                vo.setOrderNum(orderNum);

                // 计算总售票数
                Long ticketNum = pays.stream()
                        .mapToLong(Pay::getTicketNum)
                        .sum();
                vo.setTicketNum(ticketNum);

                // 计算总商品数量
                Long quantityNum = pays.stream()
                        .mapToLong(Pay::getQuantity)
                        .sum();
                vo.setQuantityNum(quantityNum);

            }
        } else {
            // 创建支付方式对象
            Pay cashPay = new Pay();
            cashPay.setName("现金");
            cashPay.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
            cashPay.setOrderNum(Math.toIntExact(slkjShiftManagement.getCashOrderNum()));
            cashPay.setTicketNum(Math.toIntExact(slkjShiftManagement.getCashTicketNum()));
            cashPay.setQuantity(Math.toIntExact(slkjShiftManagement.getCashQuantity()));
            cashPay.setReceipts(MoneyUtils.fen2Yuan(slkjShiftManagement.getCashReceipts()));
            cashPay.setRefund(MoneyUtils.fen2Yuan(slkjShiftManagement.getCashRefund()));

            Pay scanPay = new Pay();
            scanPay.setName("扫码");
            scanPay.setOrderNum(Math.toIntExact(slkjShiftManagement.getScanOrderNum()));
            scanPay.setTicketNum(Math.toIntExact(slkjShiftManagement.getScanTicketNum()));
            scanPay.setQuantity(Math.toIntExact(slkjShiftManagement.getScanQuantity()));
            scanPay.setReceipts(MoneyUtils.fen2Yuan(slkjShiftManagement.getScanForPayment()));
            scanPay.setRefund(MoneyUtils.fen2Yuan(slkjShiftManagement.getScanRefund()));
            // Pay onlinePay = new Pay();
            // onlinePay.setName("线上核销");
            // onlinePay.setOrderNum(Math.toIntExact(slkjShiftManagement.getOnlineScanOrderNum()));
            // onlinePay.setTicketNum(Math.toIntExact(slkjShiftManagement.getOnlineScanTicketNum()));
            // onlinePay.setQuantity(0);    // 示例值

            // 将这些支付方式对象添加到 vo 的 pays 列表中
            List<Pay> pays = new ArrayList<>();
            pays.add(cashPay);
            pays.add(scanPay);
            // pays.add(onlinePay);

            vo.setShiftHandover(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash() + slkjShiftManagement.getCashReceipts()));
            vo.setTotalReceipts(MoneyUtils.fen2Yuan(slkjShiftManagement.getTotalReceipts()));
            vo.setOrderNum(slkjShiftManagement.getOrderNum());
            vo.setTicketNum(slkjShiftManagement.getTicketNum());
            vo.setQuantityNum(slkjShiftManagement.getQuantityNum());
            vo.setPays(pays);

        }
        return AjaxResult.success(vo);
    }


    @Override
    public PageInfo<SlkjShiftManagement> selectSlkjShiftManagementList(SlkjShiftManagement slkjShiftManagement, Long deptId) {
        Long deptId1 = SecurityUtils.getDeptId();
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId1);
        List<SysDept> sysDepts = sysDeptMapper.selectDeptListByDeptId(sysDept.getAncestors());
        List<Long> deptIds = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        List<Long> shop = slkjShopMapper.selectShopIdByDeptId(deptIds);

        // 开启分页，目的在分页查询时，需要total，防止后续逻辑处理，导致的aop失效，total值获取错误
        Page<Object> pageExt = PageUtils.startPageExt(true);
        List<SlkjShiftManagement> shiftManagements = slkjShiftManagementMapper.selectSlkjShiftManagementLists(slkjShiftManagement, shop);

        long total = pageExt.getTotal();

        final List<SlkjShiftManagement> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(shiftManagements)) {
            Set<Long> shopIds = shiftManagements.stream().map(SlkjShiftManagement::getShopId).collect(Collectors.toSet());
            List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTimeLists(shopIds);
            Long incash = 0L;
            Long nonIncash = 0L;
            if (!CollectionUtils.isEmpty(slkjOrders)) {
                List<Long> orderIds = slkjOrders.stream()
                        .map(SlkjOrder::getOrderId).collect(Collectors.toList());
                log.info("当前登录人权限下门店订单id集合：{}", orderIds);
                List<SlkjOrderPricingSnapshot> snapshots = slkjOrderPricingSnapshotMapper.selectByOrderIds(orderIds);
                Map<Long, List<SlkjOrderPricingSnapshot>> snapMap = snapshots.stream()
                        .collect(Collectors.groupingBy(SlkjOrderPricingSnapshot::getOrderId));
                Map<String, List<SlkjOrder>> orderMap = slkjOrders.stream()
                        .collect(Collectors.groupingBy(SlkjOrder::getCreateBy));
                log.info("当前登录人权限下根据收银员为key订单集合：{}", orderMap);
                for (SlkjShiftManagement shiftManagement : shiftManagements) {
                    List<SlkjOrder> orders = orderMap.get(String.valueOf(shiftManagement.getUserId()));
                    //判断这个集合当中的订单中的createTime是否在shiftManagement的开始时间和结束时间之间，如果在，则进行计算，否则不进行计算
                    Date endTime = shiftManagement.getEndTime() != null ? shiftManagement.getEndTime() : DateUtils.getNowDate();
                    if (!orders.isEmpty()) {
                        List<SlkjOrder> orderList = orders.stream()
                                .filter(order -> order.getCreateTime().after(shiftManagement.getStartTime())
                                        && order.getCreateTime().before(endTime))
                                .collect(Collectors.toList());
                        List<Long> orderIdList = orders.stream()
                                .map(SlkjOrder::getOrderId)
                                .collect(Collectors.toList());
                        Map<String, Long> collect = orderList.stream()
                                .filter(order -> order.getPaymentType() != null && order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()))
                                .collect(Collectors.groupingBy(SlkjOrder::getPaymentType,
                                        Collectors.summingLong(o -> (long) o.getActualAmount())));

                        incash = collect.get(LakalaPaymentTypeEnum.INCASH.getCode());
                        if (incash == null) {
                            incash = 0L;
                        }
                        nonIncash = collect.entrySet().stream()
                                .filter(entry -> !entry.getKey().equals(LakalaPaymentTypeEnum.INCASH.getCode()))
                                .mapToLong(Map.Entry::getValue)
                                .sum();

                        List<SlkjOrderPricingSnapshot> matchedSnapshotsStream = orderIdList.stream()
                                .flatMap(orderId -> snapMap.getOrDefault(orderId, Collections.emptyList()).stream())
                                .collect(Collectors.toList());
                        if (!matchedSnapshotsStream.isEmpty()) {
                            Map<String, Long> map = matchedSnapshotsStream.stream().collect(Collectors.groupingBy(SlkjOrderPricingSnapshot::getItemType,
                                    Collectors.summingLong(snapshot -> (long) snapshot.getQuantity() * snapshot.getBayQuantity())));
                            Long ticket = map.get("TICKET");
                            Long goods = map.get("GOODS");
                            shiftManagement.setQuantityNum(goods);
                            shiftManagement.setTicketNum(ticket);
                        } else {
                            log.info("当前登录人权限下订单价格集合为空");
                        }
                        long count = orders.stream()
                                .filter(order -> order.getSource() != 10)
                                .count();
                        shiftManagement.setOnlineScanOrderNum(count);
                        shiftManagement.setCashReceipts(incash);
                        shiftManagement.setScanForPayment(nonIncash);
                        shiftManagement.setOrderNum((long) orders.size());
                        shiftManagement.setTotalReceipts(shiftManagement.getCashReceipts() + shiftManagement.getScanForPayment());
                        shiftManagement.setPettyCash(shiftManagement.getPettyCash());
                        shiftManagement.setShiftHandover(shiftManagement.getPettyCash() + shiftManagement.getCashReceipts());
                        result.add(shiftManagement);
                    } else {
                        shiftManagement.setOnlineScanOrderNum(0L);
                        shiftManagement.setCashReceipts(0L);
                        shiftManagement.setScanForPayment(0L);
                        shiftManagement.setOrderNum((long) orders.size());
                        shiftManagement.setTotalReceipts(shiftManagement.getCashReceipts() + shiftManagement.getScanForPayment());
                        shiftManagement.setPettyCash(shiftManagement.getPettyCash());
                        shiftManagement.setShiftHandover(shiftManagement.getPettyCash() + shiftManagement.getCashReceipts());
                        result.add(shiftManagement);
                    }

                }
            } else {
                log.info("当前登录人权限下订单为空");
                // 如果轮班管理有数据，但是订单没有数据，给一条默认数据
                SlkjShiftManagement management = new SlkjShiftManagement();
                for (SlkjShiftManagement shiftManagement : shiftManagements) {
                    management.setStartTime(shiftManagement.getStartTime());
                    management.setId(shiftManagement.getId());
                    management.setHandoverId(shiftManagement.getHandoverId());
                    management.setNickName(shiftManagement.getNickName());
                    management.setShopId(shiftManagement.getShopId());
                    management.setShopName(shiftManagement.getShopName());
                    management.setUserId(shiftManagement.getUserId());
                    management.setStatus(shiftManagement.getStatus());
                }
                result.add(management);
            }
        }

        PageInfo<SlkjShiftManagement> pageInfo = new PageInfo<>(result);
        pageInfo.setList(result);
        pageInfo.setTotal(total);
        pageInfo.setPageNum(pageExt.getPageNum());
        pageInfo.setPageSize(pageExt.getPageSize());
        return pageInfo;
    }

    @Override
    public int insertSlkjShiftManagement(SlkjShiftManagement slkjShiftManagement) {
        Long userId = slkjShiftManagement.getUserId();
        List<SlkjShiftManagement> slkjShiftManagements = slkjShiftManagementMapper.selectSlkjShiftManagementByUserId(userId);
        for (SlkjShiftManagement shiftManagement : slkjShiftManagements) {
            if (shiftManagement.getStatus().equals("0")) {
                throw new UtilException("员工还在上班中！！！！");
            }
        }
        slkjShiftManagement.setHandoverId(System.currentTimeMillis());
        slkjShiftManagement.setStartTime(DateUtils.getNowDate());
        slkjShiftManagement.setCreateBy(SecurityUtils.getUsername());
        slkjShiftManagement.setCreateTime(DateUtils.getNowDate());
        return slkjShiftManagementMapper.insertSlkjShiftManagement(slkjShiftManagement);
    }

    @Override
    public ReceiptVo updateSlkjShiftManagement(ShiftManagementDto pays, Long id) {
        SlkjShiftManagement slkjShiftManagement = slkjShiftManagementMapper.selectSlkjShiftManagementById(id);
        if (!slkjShiftManagement.getStatus().equals("0")) {
            throw new UtilException("员工已交班，禁止重复提交！！！！");
        }
        if (DateUtils.differentDays(slkjShiftManagement.getStartTime())) {
            slkjShiftManagement.setEndTime(DateUtils.getNowDate());
        } else {
            throw new UtilException("交班时间不能晚于上岗时间！！！！");
        }

        for (Pay pay : pays.getPays()) {
            if (pay.getName().equals("现金")) {
                int receipts = MoneyUtils.yuan2Fen(String.valueOf(new BigDecimal(pay.getReceipts()).subtract(new BigDecimal(pay.getRefund()))));
                int orderNum = pay.getOrderNum();
                int ticketNum = pay.getTicketNum();
                int quantity = pay.getQuantity();
                int refund = MoneyUtils.yuan2Fen(pay.getRefund());
                slkjShiftManagement.setCashReceipts((long) receipts);
                slkjShiftManagement.setCashOrderNum((long) orderNum);
                slkjShiftManagement.setCashTicketNum((long) ticketNum);
                slkjShiftManagement.setCashQuantity((long) quantity);
                slkjShiftManagement.setCashRefund((long) refund);
            } else if (pay.getName().equals("扫码")) {
                slkjShiftManagement.setScanForPayment((long) MoneyUtils.yuan2Fen(String.valueOf(new BigDecimal(pay.getReceipts()).subtract(new BigDecimal(pay.getRefund())))));
                slkjShiftManagement.setScanOrderNum((long) pay.getOrderNum());
                slkjShiftManagement.setScanTicketNum((long) pay.getTicketNum());
                slkjShiftManagement.setScanQuantity((long) pay.getQuantity());
                slkjShiftManagement.setScanRefund((long) MoneyUtils.yuan2Fen(pay.getRefund()));
            }
        }

        slkjShiftManagement.setTotalReceipts(slkjShiftManagement.getCashReceipts() + slkjShiftManagement.getScanForPayment());
        slkjShiftManagement.setOrderNum(slkjShiftManagement.getScanOrderNum() + slkjShiftManagement.getCashOrderNum());
        slkjShiftManagement.setTicketNum(slkjShiftManagement.getScanTicketNum() + slkjShiftManagement.getCashTicketNum());
        slkjShiftManagement.setQuantityNum(slkjShiftManagement.getScanQuantity() + slkjShiftManagement.getCashQuantity());
        slkjShiftManagement.setShiftHandover(slkjShiftManagement.getCashReceipts() + slkjShiftManagement.getPettyCash());
        slkjShiftManagement.setStatus("1");
        slkjShiftManagement.setUpdateBy(SecurityUtils.getUsername());
        slkjShiftManagement.setUpdateTime(DateUtils.getNowDate());
        slkjShiftManagementMapper.updateSlkjShiftManagement(slkjShiftManagement);

        ReceiptVo receiptVo = new ReceiptVo();
        receiptVo.setHandoverId(slkjShiftManagement.getHandoverId());
        receiptVo.setEndTime(slkjShiftManagement.getEndTime());
        receiptVo.setStartTime(slkjShiftManagement.getStartTime());
        receiptVo.setShopName(slkjShiftManagement.getShopName());
        receiptVo.setNickName(slkjShiftManagement.getNickName());
        receiptVo.setTotalReceipts(slkjShiftManagement.getTotalReceipts());
        receiptVo.setCashReceipts(slkjShiftManagement.getCashReceipts());
        receiptVo.setScanForPayment(slkjShiftManagement.getScanForPayment());
        receiptVo.setShiftHandover(slkjShiftManagement.getShiftHandover());
        receiptVo.setPettyCash(slkjShiftManagement.getPettyCash());

        log.info("员工交班成功，结果集：{}", JSON.toJSONString(receiptVo));
        return receiptVo;
    }

    @Override
    public List<SlkjShopVo> selectByDeptId(Long userId) {
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        Long deptId = sysUser.getDeptId();
        List<SlkjShopVo> slkjShops = shopMapper.selectSlkjShopByDeptIdList(deptId);

        if (!CollectionUtils.isEmpty(slkjShops)) {
            List<Long> shopIds = slkjShops.stream()
                    .map(SlkjShopVo::getShopId)
                    .collect(Collectors.toList());
            List<SlkjShopVo> shopList = slkjShopProjectMapper.selectShopCurrentBackgroundByShopIdList(shopIds);
            if (!CollectionUtils.isEmpty(shopList)) {
                Map<Long, SlkjShopVo> shopMap = shopList.stream()
                        .collect(Collectors.toMap(SlkjShopVo::getShopId, Function.identity()));
                for (SlkjShopVo shop : slkjShops) {
                    SlkjShopVo vo = shopMap.get(shop.getShopId());
                    if (Objects.nonNull(vo)) {
                        shop.setBackgroundUrl(vo.getBackgroundUrl());
                    }
                }
            }
        }

        return slkjShops;
    }

    @Override
    public List<SlkjShopVo> selectByDeptId() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userType = user.getUserType();
        if (!userType.equals(UserType.SHOP.getCode())) {
            List<SlkjShopVo> slkjShops = shopMapper.selectSlkjShop();
            return slkjShops;
        } else {
            Long deptId = SecurityUtils.getDeptId();
            List<SlkjShopVo> slkjShops = shopMapper.selectSlkjShopByDeptIdList(deptId);
            return slkjShops;
        }
    }

    @Override
    public List<SysUser> selectUserByDeptId(Long deptId) {
        List<SysUser> sysUsers = sysUserMapper.selectUserByDeptId(deptId);
        return sysUsers;
    }

    @Override
    public ArrayList<OrderVo> shopSort(Date startTime, Long shopId) {
        // 根据当前日期获取到当日的订单
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTime(startTime, shopId);

        // 创建一个 map 用来存放按门店分组的信息
        Map<Long, OrderVo> orderVoMap = new HashMap<>();

        // 一次性获取所有快照信息
        Map<Long, List<SlkjOrderPricingSnapshot>> snapshotMap = new HashMap<>();
        for (SlkjOrder slkjOrder : slkjOrders) {
            Long orderId = slkjOrder.getOrderId();
            List<SlkjOrderPricingSnapshot> snapshots = slkjOrderPricingSnapshotMapper.selectByOrderId(orderId);
            snapshotMap.put(orderId, snapshots);
        }

        for (SlkjOrder slkjOrder : slkjOrders) {
            Long shopIds = slkjOrder.getShopId();
            OrderVo orderVo = orderVoMap.computeIfAbsent(shopIds, id -> {
                OrderVo vo = new OrderVo();
                vo.setShopName(slkjOrder.getShopName());
                return vo;
            });

            // 获取定价快照
            List<SlkjOrderPricingSnapshot> snapshots = snapshotMap.get(slkjOrder.getOrderId());
            if (snapshots != null) {
                for (SlkjOrderPricingSnapshot snapshot : snapshots) {
                    // 根据快照计算卖品收入和门票收入
                    if (snapshot.getItemType().equals(SnapshotItemType.GOODS)) {
                        orderVo.setGoodsIncome(orderVo.getGoodsIncome() + snapshot.getUserActualAmount() * snapshot.getBayQuantity());
                    } else {
                        orderVo.setTicketIncome(orderVo.getTicketIncome() + snapshot.getUserActualAmount() * snapshot.getBayQuantity());
                    }
                    orderVo.setVisitCount(orderVo.getVisitCount() + snapshot.getQuantity() * snapshot.getBayQuantity());
                    orderVo.setTotalRevenue(orderVo.getTicketIncome() + orderVo.getGoodsIncome());
                }
            }
        }

        // 将 map 中的数据添加到 orderVos 中
        ArrayList<OrderVo> orderVos = new ArrayList<>(orderVoMap.values());
        return orderVos;
    }

    @Override
    public ShareVo orderRatio(Date startTime, Long shopId) {
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTime(startTime, shopId);
        Map<String, Integer> ticketMap = new HashMap<>();
        // 创建Map用于存储出票渠道占比
        Map<String, Integer> sourceCounts = new HashMap<>();
        // 创建Map用于存储订单状态占比
        Map<String, Integer> statusCounts = new HashMap<>();
        // 创建Map用于存储订单内容占比
        Map<String, Integer> projectCounts = new HashMap<>();
        ShareVo shareVo = new ShareVo();
        shareVo.initializeDefaults(); // 手动调用初始化方法
        for (SlkjOrder slkjOrder : slkjOrders) {
            // 出票渠道占比
            String source = String.valueOf(OrderSource.fromCode(slkjOrder.getSource()));
            sourceCounts.merge(source, 1, Integer::sum);
            // 订单状态占比
            String status = String.valueOf(OrderBusinessStatus.fromCode(slkjOrder.getBusinessStatus()));
            statusCounts.merge(status, 1, Integer::sum);
            // 订单内容占比
            String projectId = slkjOrder.getProjectName();
            projectCounts.merge(projectId, 1, Integer::sum);
            // 票档销售占比
            List<SlkjOrderPricingSnapshot> snapshots = slkjOrderPricingSnapshotMapper.selectByOrderId(slkjOrder.getOrderId());
            for (SlkjOrderPricingSnapshot snapshot : snapshots) {
                String ticketLevelName = snapshot.getTicketLevelName();
                if (ticketLevelName != null) { // 检查ticketLevelId是否为null
                    ticketMap.merge(ticketLevelName, 1, Integer::sum);
                }
            }
        }

        // 计算票档销售占比
        List<Map<String, Object>> sourceRatios = calculateRatios(sourceCounts);
        // 计算订单状态占比
        List<Map<String, Object>> statusRatios = calculateRatios(statusCounts);
        // 计算订单内容占比
        List<Map<String, Object>> projectRatios = calculateRatios(projectCounts);
        // 计算出票渠道占比
        List<Map<String, Object>> ticketLevelRatios = calculateRatios(ticketMap);

        // 设置到 ShareVo 对象
        shareVo.setTicketLevelRatios(ticketLevelRatios);
        shareVo.setSourceCounts(sourceRatios);
        shareVo.setStatusCounts(statusRatios);
        shareVo.setProjectCounts(projectRatios);
        // 调用 ShareVo 的默认初始化方法
        shareVo.initializeDefaults();
        return shareVo;
    }


    private List<Map<String, Object>> calculateRatios(Map<String, Integer> counts) {
        List<Map<String, Object>> ratios = new ArrayList<>();
        int total = counts.values().stream().reduce(0, Integer::sum);
        for (Map.Entry<String, Integer> entry : counts.entrySet()) {
            BigDecimal ratio = BigDecimal.valueOf(entry.getValue()).divide(BigDecimal.valueOf(total), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            Map<String, Object> singleRatio = new HashMap<>();
            singleRatio.put("value", ratio);
            singleRatio.put("name", entry.getKey()); // 使用原来的键作为名称
            ratios.add(singleRatio);
        }
        return ratios;
    }

    @Override
    public BusinessStatusVo period(Date startTime, Long shopId) {
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTime(startTime, shopId);
        BusinessStatusVo businessStatusVo = new BusinessStatusVo();

        // 定义时间段
        final int PERIOD_LENGTH = 1; // 每个时间段的长度（小时）
        final int PERIOD_COUNT = 24 / PERIOD_LENGTH; // 一天中的时间段数量

        // 初始化时间段计数器
        TreeMap<Integer, Integer> redeemedPerPeriod = new TreeMap<>();
        TreeMap<Integer, Integer> orderedPerPeriod = new TreeMap<>();

        for (int i = 0; i < PERIOD_COUNT; i++) {
            int periodKey = i * PERIOD_LENGTH;
            redeemedPerPeriod.put(periodKey, 0);
            orderedPerPeriod.put(periodKey, 0);
        }

        for (SlkjOrder order : slkjOrders) {
            // 计算订单创建时间所在的小时
            LocalTime orderTime = order.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalTime();
            int hour = orderTime.getHour();

            // 获取时间段键
            int periodKey = hour / PERIOD_LENGTH * PERIOD_LENGTH;

            // 更新已核销量
            if (order.getBusinessStatus().equals(OrderBusinessStatus.REDEEMED.getCode()) || order.getBusinessStatus().equals(OrderBusinessStatus.WRISTBAND_RECEIVED.getCode())
                    || order.getBusinessStatus().equals(OrderBusinessStatus.DEVICE_RECEIVED.getCode()) || order.getBusinessStatus().equals(OrderBusinessStatus.COMPLETED.getCode())) {
                redeemedPerPeriod.merge(periodKey, 1, Integer::sum);
                businessStatusVo.setTotalRedeemed(businessStatusVo.getTotalRedeemed() + 1);
            }

            // 更新下单量
            orderedPerPeriod.merge(periodKey, 1, Integer::sum);
            businessStatusVo.setTotalOrdered(businessStatusVo.getTotalOrdered() + 1);
        }

        // 设置总订单数
        businessStatusVo.setTotalRevenue(slkjOrders.size());

        // 将TreeMap赋值给BusinessStatusVo的属性
        businessStatusVo.setRedeemedPerPeriod(redeemedPerPeriod);
        businessStatusVo.setOrderedPerPeriod(orderedPerPeriod);

        return businessStatusVo;
    }

    @Override
    public RevenueVo revenue(Date startTime, Long shopId) {
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTime(startTime, shopId);
        Date originalStartTime = startTime;
        RevenueVo revenueVo = new RevenueVo();

        // 当日收入
        if (!slkjOrders.isEmpty()) {
            long goodsTotalAmount = slkjOrders.stream()
                    .filter(order -> order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()))
                    .flatMap(order -> slkjOrderPricingSnapshotMapper.selectByOrderId(order.getOrderId()).stream())
                    .filter(snapshot -> snapshot.getItemType().equals(SnapshotItemType.GOODS.getCode()))
                    .mapToLong(SlkjOrderPricingSnapshot::getUserActualAmount)
                    .sum();
            revenueVo.setGoodsIncome(MoneyUtils.fen2Yuan(goodsTotalAmount));

            long ticketTotalAmount = slkjOrders.stream()
                    .filter(order -> order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()))
                    .flatMap(order -> slkjOrderPricingSnapshotMapper.selectByOrderId(order.getOrderId()).stream())
                    .filter(snapshot -> !snapshot.getItemType().equals(SnapshotItemType.GOODS.getCode()))
                    .mapToLong(SlkjOrderPricingSnapshot::getUserActualAmount)
                    .sum();
            revenueVo.setTicketIncome(MoneyUtils.fen2Yuan(ticketTotalAmount));

            revenueVo.setTotalRevenue(MoneyUtils.fen2Yuan(goodsTotalAmount + ticketTotalAmount));
        }

        // 当月收入
        List<SlkjOrderPricingSnapshot> snapshots = slkjOrderPricingSnapshotMapper.selectSnapByShopId(shopId);
        if (CollectionUtils.isEmpty(snapshots)) {
            revenueVo.setGoodsMonthIncome("0");
            revenueVo.setTicketMonthIncome("0");
        } else {
            AtomicLong goodsAmount = new AtomicLong(0);
            AtomicLong ticketAmount = new AtomicLong(0);
            for (SlkjOrderPricingSnapshot snapshot : snapshots) {
                if (snapshot.getItemType().equals(SnapshotItemType.GOODS.getCode())) {
                    goodsAmount.addAndGet(snapshot.getUserActualAmount());
                } else if (snapshot.getItemType().equals(SnapshotItemType.TICKET.getCode())) {
                    ticketAmount.addAndGet(snapshot.getUserActualAmount());
                }
            }

            revenueVo.setGoodsMonthIncome(MoneyUtils.fen2Yuan(goodsAmount.get()));
            revenueVo.setTicketMonthIncome(MoneyUtils.fen2Yuan(ticketAmount.get()));
        }

        // 创建一个日期格式化器
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");

        // 以时间为key保存前端startTime时间前7天内所有的人次
        Map<String, String> dailyVisitCounts = new TreeMap<>(String::compareTo);
        // 以时间为key保存前端startTime时间前七天内所有的门票收入
        Map<String, String> ticketIncomeHashMap = new TreeMap<>(String::compareTo);
        // 以时间为key保存前端startTime时间前七天内所有的商品收入
        Map<String, String> goodsIncomeHashMap = new TreeMap<>(String::compareTo);

        // 计算前七天的起始日期
        Calendar thirtyDaysAgo = Calendar.getInstance();
        thirtyDaysAgo.setTime(originalStartTime);
        thirtyDaysAgo.add(Calendar.DAY_OF_MONTH, -6);  // 后退7天

        Set<Long> processedOrderIds = new HashSet<>();

        for (int i = 0; i < 7; i++) {
            Calendar day = (Calendar) thirtyDaysAgo.clone();
            day.add(Calendar.DAY_OF_MONTH, i);

            // 设置当天开始和结束时间
            Calendar dayStart = (Calendar) day.clone();
            dayStart.set(Calendar.HOUR_OF_DAY, 0);
            dayStart.set(Calendar.MINUTE, 0);
            dayStart.set(Calendar.SECOND, 0);
            dayStart.set(Calendar.MILLISECOND, 0);

            Calendar dayEnd = (Calendar) day.clone();
            dayEnd.set(Calendar.HOUR_OF_DAY, 23);
            dayEnd.set(Calendar.MINUTE, 59);
            dayEnd.set(Calendar.SECOND, 59);
            dayEnd.set(Calendar.MILLISECOND, 999);

            Date startOfDay = dayStart.getTime();
            Date endOfDay = dayEnd.getTime();

            // 查询当天的订单
            List<SlkjOrder> dailyOrders = slkjOrderMapper.selectSlkjOrderByTimes(startOfDay, endOfDay, shopId);

            // 人次
            Long visitCount = dailyOrders.stream()
                    .filter(order -> order != null && order.getBusinessStatus() != null && order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()) && order.getBusinessStatus().equals(OrderBusinessStatus.COMPLETED.getCode()))
                    .filter(order -> !processedOrderIds.contains(order.getOrderId()))
                    .flatMap(order -> slkjOrderPricingSnapshotMapper.selectByOrderId(order.getOrderId()).stream())
                    .filter(snapshot -> snapshot.getItemType().equals(SnapshotItemType.TICKET.getCode()))
                    .mapToLong(snapshot -> (long) snapshot.getBayQuantity() * snapshot.getQuantity())
                    .sum();

            // 门票收入
            long ticketIncome = dailyOrders.stream()
                    .filter(order -> order != null  && order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()))
                    .filter(order -> !processedOrderIds.contains(order.getOrderId()))
                    .flatMap(order -> slkjOrderPricingSnapshotMapper.selectByOrderId(order.getOrderId()).stream())
                    .filter(snapshot -> snapshot.getItemType().equals(SnapshotItemType.TICKET.getCode()))
                    .mapToLong(SlkjOrderPricingSnapshot::getUserActualAmount)
                    .sum();

            // 商品收入
            long goodsIncome = dailyOrders.stream()
                    .filter(order -> order != null && order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()))
                    .filter(order -> !processedOrderIds.contains(order.getOrderId()))
                    .flatMap(order -> slkjOrderPricingSnapshotMapper.selectByOrderId(order.getOrderId()).stream())
                    .filter(snapshot -> snapshot.getItemType().equals(SnapshotItemType.GOODS.getCode()))
                    .mapToLong(SlkjOrderPricingSnapshot::getUserActualAmount)
                    .sum();

            // 更新已处理的订单ID
            dailyOrders.stream()
                    .filter(order -> order != null && order.getBusinessStatus() != null && order.getBusinessStatus().equals(OrderBusinessStatus.COMPLETED.getCode()) && order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()))
                    .forEach(order -> processedOrderIds.add(order.getOrderId()));

            // 将日期转换为“月-日”格式并添加到map中
            String dateStr = sdf.format(day.getTime());
            dailyVisitCounts.put(dateStr, visitCount + "");
            ticketIncomeHashMap.put(dateStr, MoneyUtils.fen2Yuan(ticketIncome));
            goodsIncomeHashMap.put(dateStr, MoneyUtils.fen2Yuan(goodsIncome));
        }

        // 添加到RevenueVo对象中
        revenueVo.setVisitCountMap(dailyVisitCounts);
        revenueVo.setTicketIncomeMap(ticketIncomeHashMap);
        revenueVo.setGoodsIncomeMap(goodsIncomeHashMap);
        return revenueVo;
    }

    @Override
    public AjaxResult selectSlkjShiftManagemen(Long userId) {
        log.info("查询员工 [{}] 今日班次信息", userId);
        Date date = DateUtils.getNowDate();
        SlkjShiftManagement slkjShiftManagement = slkjShiftManagementMapper.selectSlkjShiftManagement(userId, date);
        if (slkjShiftManagement == null) {
            log.info("员工今日未上班");
            return AjaxResult.warn("员工今日未上班！");
        }

        final ShiftManagementVo vo = new ShiftManagementVo();
        vo.setId(slkjShiftManagement.getId());
        vo.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
        vo.setShopName(slkjShiftManagement.getShopName());
        vo.setShopId(slkjShiftManagement.getShopId());
        vo.setUserId(slkjShiftManagement.getUserId());
        vo.setNickName(slkjShiftManagement.getNickName());
        vo.setStartTime(slkjShiftManagement.getStartTime());
        vo.setEndTime(slkjShiftManagement.getEndTime());
        vo.setStatus(slkjShiftManagement.getStatus());
        vo.setDelFlag(slkjShiftManagement.getDelFlag());
        vo.setHandoverId(slkjShiftManagement.getHandoverId());

        if ("0".equals(slkjShiftManagement.getStatus())) {
            List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTimeList(slkjShiftManagement.getStartTime(), DateUtils.getNowDate());
            List<Pay> pays = new ArrayList<>();
            Pay pay = new Pay();

            // 统计退款金额
            AtomicLong cashAl = new AtomicLong(0);
            AtomicLong scanAl = new AtomicLong(0);
            if (CollectionUtils.isEmpty(slkjOrders)) {
                pay.setName("现金");
                pay.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
                pays.add(pay);

                Pay scan = new Pay();
                scan.setName("扫码");
                pays.add(scan);
                vo.setPays(pays);
                log.info("当前用户 [{}] 今日未产生订单！", userId);
            } else {
                // 最终所有返回数据，全部基于这个list
                List<SlkjOrder> nowUserOrderList = slkjOrders.stream()
                        .filter(order -> order.getCreateBy().equals(userId + "") && (order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()) ||
                                order.getPaymentStatus().equals(LakalaTradeStateEnum.PART_REFUND.name()) ||
                                order.getPaymentStatus().equals(LakalaTradeStateEnum.REFUND.name())))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(nowUserOrderList)) {
                    log.info("当前用户 [{}] 今日未产生订单！", userId);
                } else {
                    // 获取订单价格快照信息
                    Set<Long> orderIds = nowUserOrderList.stream().map(SlkjOrder::getOrderId).collect(Collectors.toSet());
                    Map<Long, List<SlkjOrderPricingSnapshot>> orderSnapMap = slkjOrderPricingSnapshotMapper.selectByOrderIds(Lists.newArrayList(orderIds))
                            .stream()
                            .collect(Collectors.groupingBy(SlkjOrderPricingSnapshot::getOrderId));

                    String oncash = "oncash", online = "online";
                    // 根据支付方式分组，如果是现金支付单独做为一个list，否则剩余的都视为线上支付
                    Map<String, List<SlkjOrder>> orderPaymentTypeMap = nowUserOrderList.stream()
                            .filter(order -> order.getSource().equals(OrderSource.SHOP.getCode()))
                            .collect(
                                    Collectors.groupingBy(order -> LakalaPaymentTypeEnum.INCASH.getCode().equals(order.getPaymentType()) ? oncash : online)
                            );

                    // 退款金额
                    nowUserOrderList.stream()
                            .filter(order -> order.getPaymentStatus().equals(LakalaTradeStateEnum.REFUND.name()) || order.getPaymentStatus().equals(LakalaTradeStateEnum.PART_REFUND.name()))
                            .forEach(order -> {
                                if (order.getPaymentType().equals(LakalaPaymentTypeEnum.INCASH.getCode())) {
                                    cashAl.addAndGet(order.getActualAmount());
                                } else {
                                    scanAl.addAndGet(order.getActualAmount());
                                }
                            });

                    // 处理现金支付
                    if (orderPaymentTypeMap.containsKey(oncash)) {
                        List<SlkjOrder> cashList = orderPaymentTypeMap.get(oncash);
                        pay.setRefund(MoneyUtils.fen2Yuan(cashAl.get()));
                        pay.setName("现金");
                        pay.setOrderNum(cashList.size());
                        pay.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
                        int goodsNum = 0;
                        int ticketNum = 0;
                        for (SlkjOrder o : cashList) {
                            List<SlkjOrderPricingSnapshot> snapshots = orderSnapMap.get(o.getOrderId());
                            // 101=门票、102=商品、103=门票+商品
                            switch (OrderType.fromCode(o.getOrderType())) {
                                case OT_101:
                                    ticketNum += snapshots.stream()
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();
                                    break;
                                case OT_102:
                                    goodsNum += snapshots.size();
                                    break;
                                case OT_103:
                                    ticketNum += snapshots.stream()
                                            .filter(i -> "TICKET".equals(i.getItemType()))
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();

                                    goodsNum += (int) snapshots.stream()
                                            .filter(i -> "GOODS".equals(i.getItemType()))
                                            .count();
                                    break;
                                default:
                                    break;
                            }
                        }
                        pay.setQuantity(goodsNum);
                        pay.setTicketNum(ticketNum);

                        long cashTotal = cashList.stream().mapToLong(SlkjOrder::getActualAmount).sum();
                        log.info("员工 [{}] 今日现金收款金额：{}分！", userId, cashTotal);
                        String yuan = MoneyUtils.fen2Yuan(cashTotal);
                        pay.setReceipts(yuan);

                        pay.setRefund(cashAl.get() > 0 ? MoneyUtils.fen2Yuan(cashAl.get()) : "0");
                        pays.add(pay);
                    } else {
                        Pay cashPay = new Pay();
                        cashPay.setName("现金");
                        cashPay.setRefund(MoneyUtils.fen2Yuan(cashAl.get()));
                        cashPay.setOrderNum(0);
                        pays.add(cashPay);
                    }


                    // 处理线上支付
                    if (orderPaymentTypeMap.containsKey(online)) {
                        Pay payScan = new Pay();
                        int goodsNum = 0;
                        int ticketNum = 0;
                        List<SlkjOrder> onlineList = orderPaymentTypeMap.get(online);
                        payScan.setName("扫码");
                        payScan.setRefund(MoneyUtils.fen2Yuan(scanAl.get()));
                        payScan.setOrderNum(onlineList.size());
                        for (SlkjOrder o : onlineList) {
                            List<SlkjOrderPricingSnapshot> snapshots = orderSnapMap.get(o.getOrderId());
                            // 101=门票、102=商品、103=门票+商品
                            switch (OrderType.fromCode(o.getOrderType())) {
                                case OT_101:
                                    ticketNum += snapshots.stream()
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();
                                    break;
                                case OT_102:
                                    goodsNum += snapshots.size();
                                    break;
                                case OT_103:
                                    ticketNum += snapshots.stream()
                                            .filter(i -> "TICKET".equals(i.getItemType()))
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();

                                    goodsNum += (int) snapshots.stream()
                                            .filter(i -> "GOODS".equals(i.getItemType()))
                                            .count();
                                    break;
                                default:
                                    break;
                            }
                        }
                        payScan.setQuantity(goodsNum);
                        payScan.setTicketNum(ticketNum);

                        long onlineTotal = onlineList.stream().mapToLong(SlkjOrder::getActualAmount).sum();
                        log.info("员工 [{}] 今日线上收款金额：{}分！", userId, onlineTotal);
                        String yuan = MoneyUtils.fen2Yuan(onlineTotal);
                        payScan.setReceipts(yuan);

                        payScan.setRefund(scanAl.get() > 0 ? MoneyUtils.fen2Yuan(scanAl.get()) : "0");
                        pays.add(payScan);
                    } else {
                        Pay scanPay = new Pay();
                        scanPay.setName("扫码");
                        scanPay.setRefund(MoneyUtils.fen2Yuan(scanAl.get()));
                        scanPay.setOrderNum(0);
                        pays.add(scanPay);
                    }

                }
                vo.setPays(pays);
            }

            pays = vo.getPays();
            // 计算应交现金
            vo.setShiftHandover(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
            if (!CollectionUtils.isEmpty(pays)) {
                Optional<Pay> paySum = pays.stream().filter(p -> p.getName().equals("现金")).findFirst();
                if (paySum.isPresent()) {
                    String receipts = paySum.get().getReceipts();
                    if (StringUtils.isNotBlank(receipts) && !"0".equals(receipts)) {
                        long total = MoneyUtils.yuan2Fen(receipts) + slkjShiftManagement.getPettyCash();
                        vo.setShiftHandover(MoneyUtils.fen2Yuan(total - cashAl.get()));
                    }
                }

                // 计算总收入，需要把退款的金额扣除
                long totalRefund = pays.stream().mapToLong(p -> MoneyUtils.yuan2Fen(p.getRefund())).sum();
                long totalReceipts = pays.stream()
                        .mapToLong(p -> MoneyUtils.yuan2Fen(p.getReceipts()))
                        .sum();
                vo.setTotalReceipts(MoneyUtils.fen2Yuan((totalReceipts - totalRefund)));

                // 计算总订单数
                Long orderNum = pays.stream()
                        .mapToLong(Pay::getOrderNum)
                        .sum();
                vo.setOrderNum(orderNum);

                // 计算总售票数
                Long ticketNum = pays.stream()
                        .mapToLong(Pay::getTicketNum)
                        .sum();
                vo.setTicketNum(ticketNum);

                // 计算总商品数量
                Long quantityNum = pays.stream()
                        .mapToLong(Pay::getQuantity)
                        .sum();
                vo.setQuantityNum(quantityNum);

            }

        } else {
            // 已交班，去交班列表查看具体信息
            return AjaxResult.warn("用户已交班，请前往交班列表查看具体信息！");
        }
        return AjaxResult.success(vo);
    }

    @Override
    public ReceiptVo receipt(Long id) {
        SlkjShiftManagement slkjShiftManagement = slkjShiftManagementMapper.selectSlkjShiftManagementById(id);
        ReceiptVo receiptVo = new ReceiptVo();
        receiptVo.setShopName(slkjShiftManagement.getShopName());
        receiptVo.setNickName(slkjShiftManagement.getNickName());
        receiptVo.setStartTime(slkjShiftManagement.getStartTime());
        receiptVo.setEndTime(slkjShiftManagement.getEndTime());
        receiptVo.setShiftHandover(slkjShiftManagement.getShiftHandover());
        receiptVo.setTotalReceipts(slkjShiftManagement.getTotalReceipts());
        receiptVo.setCashReceipts(slkjShiftManagement.getCashReceipts());
        receiptVo.setScanForPayment(slkjShiftManagement.getScanForPayment());
        receiptVo.setPettyCash(slkjShiftManagement.getPettyCash());
        receiptVo.setHandoverId(slkjShiftManagement.getHandoverId());
        return receiptVo;
    }

    @Override
    public AjaxResult handover(Long userId) {
        log.info("查询员工 [{}] 今日班次信息", userId);
        Date date = DateUtils.getNowDate();
        SlkjShiftManagement slkjShiftManagement = slkjShiftManagementMapper.selectSlkjShiftManagement(userId, date);
        if (slkjShiftManagement == null) {
            slkjShiftManagement = new SlkjShiftManagement();
            slkjShiftManagement.setUserId(userId);
            slkjShiftManagement.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
            slkjShiftManagement.setShopId(SecurityUtils.getDeptId());
            slkjShiftManagementMapper.insertSlkjShiftManagement(slkjShiftManagement);
        }

        final ShiftManagementVo vo = new ShiftManagementVo();
        vo.setId(slkjShiftManagement.getId());
        vo.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
        vo.setShopName(slkjShiftManagement.getShopName());
        vo.setShopId(slkjShiftManagement.getShopId());
        vo.setUserId(slkjShiftManagement.getUserId());
        vo.setNickName(slkjShiftManagement.getNickName());
        vo.setStartTime(slkjShiftManagement.getStartTime());
        vo.setEndTime(slkjShiftManagement.getEndTime());
        vo.setStatus(slkjShiftManagement.getStatus());
        vo.setDelFlag(slkjShiftManagement.getDelFlag());
        vo.setHandoverId(slkjShiftManagement.getHandoverId());

        if ("0".equals(slkjShiftManagement.getStatus())) {
            List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTimeList(slkjShiftManagement.getStartTime(), DateUtils.getNowDate());
            List<Pay> pays = new ArrayList<>();
            Pay pay = new Pay();

            if (CollectionUtils.isEmpty(slkjOrders)) {
                pay.setName("现金");
                pay.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
                pays.add(pay);

                Pay scan = new Pay();
                scan.setName("扫码");
                pays.add(scan);
                vo.setPays(pays);
                log.info("当前用户 [{}] 今日未产生订单！", userId);
            } else {
                // 最终所有返回数据，全部基于这个list
                List<SlkjOrder> nowUserOrderList = slkjOrders.stream()
                        .filter(order -> order.getCreateBy().equals(userId + "") && (order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name()) ||
                                order.getPaymentStatus().equals(LakalaTradeStateEnum.PART_REFUND.name()) ||
                                order.getPaymentStatus().equals(LakalaTradeStateEnum.REFUND.name())))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(nowUserOrderList)) {
                    log.info("当前用户 [{}] 今日未产生订单！", userId);
                } else {
                    // 获取订单价格快照信息
                    Set<Long> orderIds = nowUserOrderList.stream().map(SlkjOrder::getOrderId).collect(Collectors.toSet());
                    Map<Long, List<SlkjOrderPricingSnapshot>> orderSnapMap = slkjOrderPricingSnapshotMapper.selectByOrderIds(Lists.newArrayList(orderIds))
                            .stream()
                            .collect(Collectors.groupingBy(SlkjOrderPricingSnapshot::getOrderId));

                    String oncash = "oncash", online = "online";
                    // 根据支付方式分组，如果是现金支付单独做为一个list，否则剩余的都视为线上支付
                    Map<String, List<SlkjOrder>> orderPaymentTypeMap = nowUserOrderList.stream()
                            .filter(order -> order.getSource().equals(OrderSource.SHOP.getCode()))
                            .collect(
                                    Collectors.groupingBy(order -> LakalaPaymentTypeEnum.INCASH.getCode().equals(order.getPaymentType()) ? oncash : online)
                            );

                    // 统计退款金额
                    AtomicLong cash = new AtomicLong(0);
                    AtomicLong scan = new AtomicLong(0);
                    nowUserOrderList.stream()
                            .filter(order -> order.getPaymentStatus().equals(LakalaTradeStateEnum.REFUND.name()) || order.getPaymentStatus().equals(LakalaTradeStateEnum.PART_REFUND.name()))
                            .forEach(order -> {
                                if (order.getPaymentType().equals(LakalaPaymentTypeEnum.INCASH.getCode())) {
                                    cash.addAndGet(order.getActualAmount());
                                } else {
                                    scan.addAndGet(order.getActualAmount());
                                }
                            });

                    // 处理现金支付
                    if (orderPaymentTypeMap.containsKey(oncash)) {
                        List<SlkjOrder> cashList = orderPaymentTypeMap.get(oncash);
                        pay.setRefund(MoneyUtils.fen2Yuan(cash.get()));
                        pay.setName("现金");
                        pay.setOrderNum(cashList.size());
                        pay.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
                        int goodsNum = 0;
                        int ticketNum = 0;
                        for (SlkjOrder o : cashList) {
                            List<SlkjOrderPricingSnapshot> snapshots = orderSnapMap.get(o.getOrderId());
                            // 101=门票、102=商品、103=门票+商品
                            switch (OrderType.fromCode(o.getOrderType())) {
                                case OT_101:
                                    ticketNum += snapshots.stream()
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();
                                    break;
                                case OT_102:
                                    goodsNum += snapshots.size();
                                    break;
                                case OT_103:
                                    ticketNum += snapshots.stream()
                                            .filter(i -> "TICKET".equals(i.getItemType()))
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();

                                    goodsNum += (int) snapshots.stream()
                                            .filter(i -> "GOODS".equals(i.getItemType()))
                                            .count();
                                    break;
                                default:
                                    break;
                            }
                        }
                        pay.setQuantity(goodsNum);
                        pay.setTicketNum(ticketNum);

                        long cashTotal = cashList.stream().mapToLong(SlkjOrder::getActualAmount).sum();
                        log.info("员工 [{}] 今日现金收款金额：{}分！", userId, cashTotal);
                        String yuan = MoneyUtils.fen2Yuan(cashTotal);
                        pay.setReceipts(yuan);

                        pay.setRefund(cash.get() > 0 ? MoneyUtils.fen2Yuan(cash.get()) : "0");
                        pays.add(pay);
                    } else {
                        Pay cashPay = new Pay();
                        cashPay.setName("现金");
                        cashPay.setRefund(MoneyUtils.fen2Yuan(scan.get()));
                        cashPay.setOrderNum(0);
                        pays.add(cashPay);
                    }


                    // 处理线上支付
                    if (orderPaymentTypeMap.containsKey(online)) {
                        Pay payScan = new Pay();
                        int goodsNum = 0;
                        int ticketNum = 0;
                        List<SlkjOrder> onlineList = orderPaymentTypeMap.get(online);
                        payScan.setName("扫码");
                        payScan.setRefund(MoneyUtils.fen2Yuan(scan.get()));
                        payScan.setOrderNum(onlineList.size());
                        for (SlkjOrder o : onlineList) {
                            List<SlkjOrderPricingSnapshot> snapshots = orderSnapMap.get(o.getOrderId());
                            // 101=门票、102=商品、103=门票+商品
                            switch (OrderType.fromCode(o.getOrderType())) {
                                case OT_101:
                                    ticketNum += snapshots.stream()
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();
                                    break;
                                case OT_102:
                                    goodsNum += snapshots.size();
                                    break;
                                case OT_103:
                                    ticketNum += snapshots.stream()
                                            .filter(i -> "TICKET".equals(i.getItemType()))
                                            .mapToInt(snap -> snap.getQuantity() * snap.getBayQuantity())
                                            .sum();

                                    goodsNum += (int) snapshots.stream()
                                            .filter(i -> "GOODS".equals(i.getItemType()))
                                            .count();
                                    break;
                                default:
                                    break;
                            }
                        }
                        payScan.setQuantity(goodsNum);
                        payScan.setTicketNum(ticketNum);

                        long onlineTotal = onlineList.stream().mapToLong(SlkjOrder::getActualAmount).sum();
                        log.info("员工 [{}] 今日线上收款金额：{}分！", userId, onlineTotal);
                        String yuan = MoneyUtils.fen2Yuan(onlineTotal);
                        payScan.setReceipts(yuan);

                        payScan.setRefund(scan.get() > 0 ? MoneyUtils.fen2Yuan(scan.get()) : "0");
                        pays.add(payScan);
                    } else {
                        Pay scanPay = new Pay();
                        scanPay.setName("扫码");
                        scanPay.setRefund(MoneyUtils.fen2Yuan(scan.get()));
                        scanPay.setOrderNum(0);
                        pays.add(scanPay);
                    }

                }
                vo.setPays(pays);
            }


            Map<Long, Map<String, List<SlkjOrder>>> ordersGroupedByShopAndStatus = slkjOrders.stream()
                    .filter(order -> order.getSource().equals(OrderSource.SHOP.getCode()) && order.getCreateBy().equals(userId + "")) //只处理门店订单，当前用户手上产生的订单数据
                    .collect(Collectors.groupingBy(SlkjOrder::getShopId,
                            Collectors.groupingBy(SlkjOrder::getPaymentStatus)));

            pays = vo.getPays();

            // 计算应交现金
            vo.setShiftHandover(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
            if (!CollectionUtils.isEmpty(pays)) {
                Optional<Pay> paySum = pays.stream().filter(p -> p.getName().equals("现金")).findFirst();
                if (paySum.isPresent()) {
                    String receipts = paySum.get().getReceipts();
                    if (StringUtils.isNotBlank(receipts) && !"0".equals(receipts)) {
                        long total = MoneyUtils.yuan2Fen(receipts) + slkjShiftManagement.getPettyCash();
                        vo.setShiftHandover(MoneyUtils.fen2Yuan(total));
                    }
                }


                // 计算总收入
                long totalReceipts = pays.stream()
                        .mapToLong(p -> MoneyUtils.yuan2Fen(p.getReceipts()))
                        .sum();
                vo.setTotalReceipts(MoneyUtils.fen2Yuan(totalReceipts));

                // 计算总订单数
                Long orderNum = pays.stream()
                        .mapToLong(Pay::getOrderNum)
                        .sum();
                vo.setOrderNum(orderNum);

                // 计算总售票数
                Long ticketNum = pays.stream()
                        .mapToLong(Pay::getTicketNum)
                        .sum();
                vo.setTicketNum(ticketNum);

                // 计算总商品数量
                Long quantityNum = pays.stream()
                        .mapToLong(Pay::getQuantity)
                        .sum();
                vo.setQuantityNum(quantityNum);

            }


        } else {
            // 创建支付方式对象
            Pay cashPay = new Pay();
            cashPay.setName("现金");
            cashPay.setPettyCash(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash()));
            cashPay.setOrderNum(Math.toIntExact(slkjShiftManagement.getCashOrderNum()));
            cashPay.setTicketNum(Math.toIntExact(slkjShiftManagement.getCashTicketNum()));
            cashPay.setQuantity(Math.toIntExact(slkjShiftManagement.getCashQuantity()));
            cashPay.setReceipts(MoneyUtils.fen2Yuan(slkjShiftManagement.getCashReceipts()));
            cashPay.setRefund(MoneyUtils.fen2Yuan(slkjShiftManagement.getCashRefund()));

            Pay scanPay = new Pay();
            scanPay.setName("扫码");
            scanPay.setOrderNum(Math.toIntExact(slkjShiftManagement.getScanOrderNum()));
            scanPay.setTicketNum(Math.toIntExact(slkjShiftManagement.getScanTicketNum()));
            scanPay.setQuantity(Math.toIntExact(slkjShiftManagement.getScanQuantity()));
            scanPay.setReceipts(MoneyUtils.fen2Yuan(slkjShiftManagement.getScanForPayment()));
            scanPay.setRefund(MoneyUtils.fen2Yuan(slkjShiftManagement.getScanRefund()));

            // Pay onlinePay = new Pay();
            // onlinePay.setName("线上核销");
            // onlinePay.setOrderNum(Math.toIntExact(slkjShiftManagement.getOnlineScanOrderNum()));
            // onlinePay.setTicketNum(Math.toIntExact(slkjShiftManagement.getOnlineScanTicketNum()));
            // onlinePay.setQuantity(0);    // 示例值

            // 将这些支付方式对象添加到 vo 的 pays 列表中
            List<Pay> pays = new ArrayList<>();
            pays.add(cashPay);
            pays.add(scanPay);
            // pays.add(onlinePay);

            vo.setShiftHandover(MoneyUtils.fen2Yuan(slkjShiftManagement.getPettyCash() + slkjShiftManagement.getCashReceipts()));
            vo.setTotalReceipts(MoneyUtils.fen2Yuan(slkjShiftManagement.getTotalReceipts()));
            vo.setOrderNum(slkjShiftManagement.getOrderNum());
            vo.setTicketNum(slkjShiftManagement.getTicketNum());
            vo.setQuantityNum(slkjShiftManagement.getQuantityNum());
            vo.setPays(pays);

        }
        return AjaxResult.success(vo);
    }

    @Override
    public List<SlkjShiftManagement> exportSlkjShiftManagementList(SlkjShiftManagement slkjShiftManagement, Long deptId) {
        Long deptId1 = SecurityUtils.getDeptId();
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId1);
        List<SysDept> sysDepts = sysDeptMapper.selectDeptListByDeptId(sysDept.getAncestors());
        List<Long> deptIds = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        List<Long> shop = slkjShopMapper.selectShopIdByDeptId(deptIds);

        List<SlkjShiftManagement> shiftManagements = slkjShiftManagementMapper.selectSlkjShiftManagementLists(slkjShiftManagement, shop);

        final List<SlkjShiftManagement> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(shiftManagements)) {
            Set<Long> shopIds = shiftManagements.stream().map(SlkjShiftManagement::getShopId).collect(Collectors.toSet());
            List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByTimeLists(shopIds);
            Long incash = 0L;
            Long nonIncash = 0L;
            if (!CollectionUtils.isEmpty(slkjOrders)) {
                List<Long> orderIds = slkjOrders.stream()
                        .map(SlkjOrder::getOrderId).collect(Collectors.toList());
                log.info("当前登录人权限下门店订单id集合：{}", orderIds);
                List<SlkjOrderPricingSnapshot> snapshots = slkjOrderPricingSnapshotMapper.selectByOrderIds(orderIds);
                Map<Long, List<SlkjOrderPricingSnapshot>> snapMap = snapshots.stream()
                        .collect(Collectors.groupingBy(SlkjOrderPricingSnapshot::getOrderId));
                Map<String, List<SlkjOrder>> orderMap = slkjOrders.stream()
                        .collect(Collectors.groupingBy(SlkjOrder::getCreateBy));
                log.info("当前登录人权限下根据收银员为key订单集合：{}", orderMap);
                for (SlkjShiftManagement shiftManagement : shiftManagements) {
                    List<SlkjOrder> orders = orderMap.get(String.valueOf(shiftManagement.getUserId()));
                    //判断这个集合当中的订单中的createTime是否在shiftManagement的开始时间和结束时间之间，如果在，则进行计算，否则不进行计算
                    Date endTime = shiftManagement.getEndTime() != null ? shiftManagement.getEndTime() : DateUtils.getNowDate();
                    if (!orders.isEmpty()) {
                        List<SlkjOrder> orderList = orders.stream()
                                .filter(order -> order.getCreateTime().after(shiftManagement.getStartTime())
                                        && order.getCreateTime().before(endTime))
                                .collect(Collectors.toList());
                        List<Long> orderIdList = orders.stream()
                                .map(SlkjOrder::getOrderId)
                                .collect(Collectors.toList());
                        Map<String, Long> collect = orderList.stream()
                                .filter(order -> order.getPaymentType() != null)
                                .collect(Collectors.groupingBy(SlkjOrder::getPaymentType,
                                        Collectors.summingLong(o -> (long) o.getActualAmount())));

                        incash = collect.get(LakalaPaymentTypeEnum.INCASH.getCode());
                        if (incash == null) {
                            incash = 0L;
                        }
                        nonIncash = collect.entrySet().stream()
                                .filter(entry -> !entry.getKey().equals(LakalaPaymentTypeEnum.INCASH.getCode()))
                                .mapToLong(Map.Entry::getValue)
                                .sum();

                        List<SlkjOrderPricingSnapshot> matchedSnapshotsStream = orderIdList.stream()
                                .flatMap(orderId -> snapMap.getOrDefault(orderId, Collections.emptyList()).stream())
                                .collect(Collectors.toList());
                        if (!matchedSnapshotsStream.isEmpty()) {
                            Map<String, Long> map = matchedSnapshotsStream.stream().collect(Collectors.groupingBy(SlkjOrderPricingSnapshot::getItemType,
                                    Collectors.summingLong(snapshot -> (long) snapshot.getQuantity() * snapshot.getBayQuantity())));
                            Long ticket = map.get("TICKET");
                            Long goods = map.get("GOODS");
                            shiftManagement.setQuantityNum(goods);
                            shiftManagement.setTicketNum(ticket);
                        } else {
                            log.info("当前登录人权限下订单价格集合为空");
                        }
                        long count = orders.stream()
                                .filter(order -> order.getSource() != 10)
                                .count();
                        shiftManagement.setOnlineScanOrderNum(count);
                        shiftManagement.setCashReceipts(incash);
                        shiftManagement.setScanForPayment(nonIncash);
                        shiftManagement.setOrderNum((long) orders.size());
                        shiftManagement.setTotalReceipts(shiftManagement.getCashReceipts() + shiftManagement.getScanForPayment());
                        shiftManagement.setPettyCash(shiftManagement.getPettyCash());
                        shiftManagement.setShiftHandover(shiftManagement.getPettyCash() + shiftManagement.getCashReceipts());
                        result.add(shiftManagement);
                    } else {
                        shiftManagement.setOnlineScanOrderNum(0L);
                        shiftManagement.setCashReceipts(0L);
                        shiftManagement.setScanForPayment(0L);
                        shiftManagement.setOrderNum((long) orders.size());
                        shiftManagement.setTotalReceipts(shiftManagement.getCashReceipts() + shiftManagement.getScanForPayment());
                        shiftManagement.setPettyCash(shiftManagement.getPettyCash());
                        shiftManagement.setShiftHandover(shiftManagement.getPettyCash() + shiftManagement.getCashReceipts());
                        result.add(shiftManagement);
                    }

                }
            } else {
                log.info("当前登录人权限下订单为空");
                // 如果轮班管理有数据，但是订单没有数据，给一条默认数据
                SlkjShiftManagement management = new SlkjShiftManagement();
                for (SlkjShiftManagement shiftManagement : shiftManagements) {
                    management.setStartTime(shiftManagement.getStartTime());
                    management.setId(shiftManagement.getId());
                    management.setHandoverId(shiftManagement.getHandoverId());
                    management.setNickName(shiftManagement.getNickName());
                    management.setShopId(shiftManagement.getShopId());
                    management.setShopName(shiftManagement.getShopName());
                    management.setUserId(shiftManagement.getUserId());
                    management.setStatus(shiftManagement.getStatus());
                }
                result.add(management);
            }
        }
        return result;
    }

}